const bodyParser = require('body-parser');
const express = require('express');
const app = express();

const router = express.Router();

const port = 3000;


app.use(bodyParser.json())

global.store = {
    count: 0,
    status: false,
};

router.use(async(req, res, next)=>{
    console.log(req.url);
    console.log(req.body);
    console.log('req中间件');
    if(req.url === '/set') {
        global.store.status = true; 
        const r = await test();     
        console.log(r);   
        // res.send({
        //     data: r + '- req中间件',
        //     code: 1
        // })
        global.store.status = false; 
        next();
    }else {
       const storeIterval =  setInterval(()=>{
            if(!global.store.status) {
                console.log(global.store.status, '123');
                next();
                clearInterval(storeIterval);
            }
        }, 10)
    }
})

router.get('/', (req, res)=>res.send('hello world'))

router.post('/set',  (req, res)=>{
    // console.log(req, 'req');
    res.send({
        data: '1',
        code: 0
    })
})

router.get('/get', async (req, res)=>{
    console.log(req.query, 'req')
    try {
        const r = await test1();
        res.send({
            data: r,
            code: 0
        })
    }catch(err){

    }
})

function test() {
   return new Promise((resolve, reject)=>{
    setTimeout(()=>{
        resolve('这个是测试数据req')
    }, 10000)
   })
}

function test1() {
    return new Promise((resolve, reject)=>{
     setTimeout(()=>{
         resolve('这个是测试数据get')
     }, 1000)
    })
 }

app.use(router)

app.listen(port, ()=>{
    console.log('启动端口3000');
})
